#!/usr/bin/env python
# -*- coding: utf-8 -*-

import struct
try:
    import cPickle as pickle
except:
    import pickle

class Socket(object):
    '''收发指令包的socket，包装了系统socket'''
    def __init__(self, socket):
        self.socket=socket

    def send(self, cmd, data=None):
        '''发送数据，有错误时设置ready状态为False'''
        #用pickle打包
        pacdata=pickle.dumps([cmd, data])

        #先发送长度再发送数据，可合理接收变长包，防止粘包
        sizedata=struct.pack('!i', len(pacdata))
        self.socket.send(sizedata)
        self.socket.send(pacdata)

    def recv(self):
        '''接收数据，有错误时设置ready状态为False'''
        #先接收数据包长度
        sizedata=self.socket.recv(4)
        if not sizedata:
            raise Exception('Connection close.')
        (pacsize, )=struct.unpack('!i', sizedata)
        
        #再接收指令数据包
        pacdata=self.socket.recv(pacsize)
        if not pacdata:
            raise Exception('Connection close.')
        else:
            cmd, data=pickle.loads(pacdata)
            return cmd, data
    
    def close(self):
        return self.socket.close()

if __name__ == '__main__':
    cmd, data=TAKECARD, [1, 2, 3, 4, dict(name='a', id=100)]
    pacdata=pickle.dumps([cmd, data])
    print pacdata, len(pacdata)
    print pickle.loads(pacdata)
